package cn.xiehang.SoundSight;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;

public class ProgressRequestBody extends RequestBody {

    private final File file;
    private final MediaType contentType;
    private final ProgressListener listener;

    public ProgressRequestBody(File file, MediaType contentType, ProgressListener listener) {

        this.file = file;
        this.contentType = contentType;
        this.listener = listener;
    }

    @Override
    public MediaType contentType() {
        return contentType;
    }

    @Override
    public long contentLength() {
        return file.length();
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        long fileLength = file.length();
        byte[] buffer = new byte[4096];
        try (InputStream in = new FileInputStream(file)) {
            long uploaded = 0;
            int read;
            while ((read = in.read(buffer)) != -1) {
                uploaded += read;
                sink.write(buffer, 0, read);
                listener.onProgress(uploaded, fileLength);
            }
        }
    }

    public interface ProgressListener {
        void onProgress(long bytesWritten, long totalBytes);
    }
}